//
//  JuNengLolViewController.m
//  HongFuShop
//
//  Created by chirui on 2017/8/9.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "JuNengLolViewController.h"

@interface JuNengLolViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIWebViewDelegate>
{
    
    UITableView * _tableView;
    NSMutableArray * _cellHeightArray;
    NSMutableArray * _heardHeightArray;
    NSMutableArray * _dataArray;
    UITextField * _commentText;
    UIView * commentTextView;
    UITextField * aginTextView;
    int _page;
    int _totailPage;
    
    NSInteger height;
    UIWebView * _webView;
    
    NSString * url;
}


@end

@implementation JuNengLolViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _page = 1;
    
    _dataArray = @[].mutableCopy;
    TitleView(@"详情");
    
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,WIDTH,50)];
    _webView.scalesPageToFit = YES;
    _webView.delegate = self;
    _webView.scrollView.bounces=NO;
    _webView.scrollView.showsHorizontalScrollIndicator = NO;
    _webView.scrollView.scrollEnabled = NO;
    
    self.view.backgroundColor =[UIColor whiteColor];
   
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_public_return" target:self action:@selector(backButton)];
    
    
    
    [self creatTableView];
    [self creatTextFieldView];
    [self getDataRequest];
    [self getNetWorking];
    
}

-(void)backButton {
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)creatTextFieldView {
    
    UIView * endView =[[UIView alloc]initWithFrame:CGRectMake(0, HEIGHT -48-64, WIDTH, 48)];
    endView.backgroundColor = [UIColor whiteColor];
    _commentText = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, WIDTH-100, 28)];
    _commentText.placeholder =@"说点什么吧";
    _commentText.font =[UIFont systemFontOfSize:15];
    _commentText.borderStyle = UITextBorderStyleRoundedRect;
    [endView addSubview:_commentText];
    
    UIButton * sendBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    sendBtn.frame = CGRectMake(WIDTH -80, 9, 60, 30);
    [sendBtn setBackgroundImage:ImageName(@"img_home_nav_bg") forState:UIControlStateNormal];
    sendBtn.layer.cornerRadius = 5.f;
    sendBtn.layer.masksToBounds =YES;
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sendBtn.titleLabel.font =[UIFont systemFontOfSize:15];
    [sendBtn addTarget:self action:@selector(sendClick:) forControlEvents:UIControlEventTouchUpInside];
    [endView addSubview:sendBtn];
    
    [self.view addSubview:endView];
    
}

-(void)sendClick:(UIButton *)btn {
    
    
    
    [_commentText resignFirstResponder];
    
    if (verifTokenAndEnter) {
        
        if (_commentText.text==nil||_commentText.text.length<1) {
            
            [SHJudgeTools MBProgressHUDPromptWith:@"评论文字不能为空" On:self.view];
            
            return;
        }
        
        [self addCommentNetWorking];
        
    }else {
        LogingViewController * enter =[[LogingViewController alloc]init];
        [self.navigationController pushViewController:enter animated:YES];
        
    }
    
    
}


-(void)creatTableView {
    
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT - 64-48) style:UITableViewStyleGrouped];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    
    UIView *view = [[UIView alloc]init];
    _tableView.tableFooterView = view;
    
    [self.view addSubview:_tableView];
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        _page =1;
        [self getDataRequest];
        
    }];
    _tableView.mj_header =header;
    
    //暂时隐藏
    MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getDataRequest];
        
    }];
    if (_dataArray.count<10) {
        footer.stateLabel.text=nil;
    }
    
        footer.automaticallyRefresh = YES;
    _tableView.mj_footer =footer;
    
    [self.view addSubview:_tableView];
    
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section==0) {
        
        return 1;
        
    }else {
        
        return _dataArray.count;
    }
}

-(void)creatWEBfor:(NSString *)urlStr {
    
    
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] intValue];
    webView.frame = CGRectMake(0, 0, WIDTH, height);
    [_tableView reloadData];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section==0) {
        return _webView.frame.size.height;
    }else {
        NSDictionary * dic = _dataArray[indexPath.row];
        
        UILabel *contentLabel;
        
         NSString * replyStr = dic[@"reply"];
        
        if (replyStr.length>0||replyStr!=nil) {
            
            contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(20,60 , WIDTH -40, 20)];
            contentLabel.text = dic[@"comment"];
            contentLabel.textColor = [UIColor blackColor];
            contentLabel.numberOfLines = 3;
            contentLabel.font = [UIFont systemFontOfSize:15];
            [contentLabel sizeToFit];
            
            UILabel * replyLabel =[[UILabel alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(contentLabel.frame)+10,WIDTH -40, 20)];
            replyLabel.text = [NSString stringWithFormat:@"【回复】:%@",dic[@"reply"]];
            replyLabel.textColor = Color(123, 173, 190);
            replyLabel.numberOfLines = 4;
            replyLabel.font = [UIFont systemFontOfSize:15];
            [replyLabel sizeToFit];
            
            return CGRectGetMaxY(replyLabel.frame)+20;
            
        }else {
            
            UILabel *contentLabel;
            
            contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(20,60 , WIDTH -40, 20)];
            
            contentLabel.text = dic[@"comment"];
            contentLabel.textColor = [UIColor blackColor];
            contentLabel.numberOfLines = 3;
            contentLabel.font = [UIFont systemFontOfSize:15];
            [contentLabel sizeToFit];
            
            return CGRectGetMaxY(contentLabel.frame)+20;
        }
    }

    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 0.01;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * cellId =@"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }else{
        while ([cell.contentView.subviews lastObject]) {
            [[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //    NSDictionary * dic = _dataArray[indexPath.row];
    
    if (indexPath.section==0) {
        
        [cell.contentView addSubview:_webView];
        return cell;
        
    }else {
        
        NSDictionary * dic = _dataArray[indexPath.row];
        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(10, 5, WIDTH - 20, 2)];
        
        view.clipsToBounds = YES;
        view.layer.cornerRadius = 5.f;
        [cell.contentView addSubview:view];
        
        
        UIImageView * userImage =[[UIImageView alloc]initWithFrame:CGRectMake(0, 7, 50, 50)];
        userImage.layer.cornerRadius = 25.f;
        userImage.layer.masksToBounds = YES;
        [userImage sd_setImageWithURL:[NSURL URLWithString:dic[@"avatar"]] placeholderImage:[UIImage imageNamed:@"img_user_default"]];
        [view addSubview:userImage];
        
        
        UILabel * name =[[UILabel alloc]initWithFrame:CGRectMake(55, 9, 200, 20)];
        name.font =[UIFont systemFontOfSize:15];
        name.textColor = [UIColor blackColor];
        
        name.text = dic[@"user_name"];
        
        [view addSubview:name];
        
        UILabel * date =[[UILabel alloc]initWithFrame:CGRectMake(55, 39,WIDTH-70, 15)];
        date.font =[UIFont systemFontOfSize:13];
        date.textColor = [UIColor lightGrayColor];
        date.text = dic[@"comment_time"];
        [view addSubview:date];
        
        
        
        UILabel *contentLabel;
        contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(10,CGRectGetMaxY(date.frame)+10 , CGRectGetWidth(view.frame)-20, 20)];
        
        contentLabel.text = dic[@"comment"];
        contentLabel.textColor = [UIColor blackColor];
        contentLabel.numberOfLines = 3;
        contentLabel.font = [UIFont systemFontOfSize:15];
        [contentLabel sizeToFit];
        [view addSubview:contentLabel];
        
        
        NSString * replyStr = dic[@"reply"];
        
        if (replyStr.length>0||replyStr!=nil) {
            
            UILabel * replyLabel =[[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(contentLabel.frame)+10, CGRectGetWidth(view.frame)-20, 20)];
            replyLabel.textColor = [UIColor grayColor] ;
            replyLabel.text = [NSString stringWithFormat:@"【回复】:%@",dic[@"reply"]];
            replyLabel.attributedText = [SHJudgeTools changeColor:[NSString stringWithFormat:@"【回复】: %@",dic[@"reply"]] partStr:@"【回复】:" color:RGB(0x4990aa) font:14];
            
            replyLabel.numberOfLines = 4;
            replyLabel.font = [UIFont systemFontOfSize:14];
            [replyLabel sizeToFit];
            [view addSubview:replyLabel];
            
            view.frame = CGRectMake(10, 5, self.view.frame.size.width - 20, CGRectGetMaxY(replyLabel.frame) + 20);
        }else {
            
            view.frame = CGRectMake(10, 5, self.view.frame.size.width - 20, CGRectGetMaxY(contentLabel.frame) + 20);
        }
    }
    return cell;
}


// 网络请求
-(void)getNetWorking {
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",NetWorkAddress_api,get_newsDetails_api];
    NSDictionary * dic = @{@"news_id":self.newsIdStr
                           };
    
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:parametersStr  andparameters:dic  Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]==200) {
            
            url = responseObject[@"datas"][@"url"];
            
            [self creatWEBfor:url];
            
        } else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        [_tableView reloadData];
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
        
    }];
    //
    
}

-(void)getDataRequest{
    
    
    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_tableView.mj_footer setState: MJRefreshStateNoMoreData];
            
            return ;
        }
    }
    NSDictionary * dic = @{
                           @"page":[NSString stringWithFormat:@"%d",_page],
                           @"page_num":@"10",
                           @"news_id":self.newsIdStr
                           };
    
    //    SHuiMBhubNoTimeStr(@"正在加载...");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(newsComment_list_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            _totailPage = [SHJudgeTools totailpageNumberForTotailNumber:responseObject[@"datas"][@"total_count"]];
            
    
            if (_page==1) {
                
                if (_dataArray) {
                    
                    [_dataArray removeAllObjects];
                }
                if ([responseObject[@"datas"][@"list"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"list"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }else {
                
                if ([responseObject[@"datas"][@"list"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"list"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
                if (_dataArray.count>0) {
                    
                    if (_dataArray.count<10) {
                        
                        _tableView.mj_footer.hidden = YES;
                    }else {
                        _tableView.mj_footer.hidden = NO;
                    }
                }else {
                    _tableView.mj_footer.hidden = YES;
                    
                }
                [_tableView.mj_header endRefreshing];
                [_tableView.mj_footer endRefreshing];
                [_tableView reloadData];
                
            });
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误请重试！");
    }];
}

// 评论
-(void)addCommentNetWorking {
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",NetWorkAddress_api,add_newsComment_api];
    NSDictionary * dic = @{@"news_id":self.newsIdStr,
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"content":_commentText.text
                           };
    
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:parametersStr  andparameters:dic  Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]==200) {
           
            _commentText.text = nil;
            SHuiMBhudTextTimeStr(@"提交成功，等待后台审核！");
            
        } else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
//        [_tableView reloadData];
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
        
    }];
  
    
}

@end
